package com.dianrui.fmi.activity;

import android.app.Dialog;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.dianrui.fmi.R;
import com.dianrui.fmi.event.RfreshStockDeal;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 买入
 */
public class BuySimulatedTransactionActivity extends BaseActivity {
    private String symbold, name, prices, updowns;
    private boolean flag = false;//标记edittext不会死循环
    private String buyMark = "";
    private String select = "";

    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.change)
    TextView change;
    @BindView(R.id.updown)
    TextView updown;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.buy_cb)
    CheckBox buyCb;
    @BindView(R.id.sale_cb)
    CheckBox saleCb;
    @BindView(R.id.stuck_name)
    TextView stuckName;

    @BindView(R.id.show_price)
    EditText showPrice;
    @BindView(R.id.show_number)
    EditText showNumber;

    @Override
    public int getContentViewId() {
        return R.layout.activity_buy_simulated_transaction;
    }

    @Override
    public void initView() {
        title.setText(getString(R.string.buy_simulating_trade));
        if (getIntent() != null && getIntent().getExtras() != null) {
            symbold = getIntent().getStringExtra("symbold");
            name = getIntent().getStringExtra("stockname");
            prices = getIntent().getStringExtra("price");
            updowns = getIntent().getStringExtra("zf");
        }
        buyMark = "Purchase";
        select = "1";
        stuckName.setText(name);
        price.setText(prices);
        showPrice.setText(prices);
        if (updowns.contains("-")) {
            updown.setText("-" + updowns);
            updown.setTextColor(Color.GREEN);
        } else {
            updown.setText(updowns);
            updown.setTextColor(Color.RED);
        }
        showPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (flag || TextUtils.isEmpty(s.toString())) {
                    return;
                }
                flag = true;
                float number = Float.valueOf(s.toString());
                if (number <= 0.00 || number <= 0) {
                    ToastUtil.showToast("Do not Input Zero point Zero");
                    showPrice.setText("");
                } else {
                    showPrice.setText(s + "");
                    showPrice.setSelection(showPrice.getText().length());
                }
                flag = false;

            }
        });

        showNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (flag || TextUtils.isEmpty(s.toString())) {
                    return;
                }
                flag = true;
                int number = Integer.parseInt(s.toString());
                if (number <= 0) {
                    ToastUtil.showToast("Do not Input Zero");
                    showNumber.setText("");
                } else if (number >= 20000) {
                    ToastUtil.showToast("Number is already 200000!");
                    showNumber.setText("");
                } else {
                    showNumber.setText(s + "");
                    showNumber.setSelection(showNumber.getText().length());
                }
                flag = false;
            }
        });


    }


    @OnClick({R.id.back, R.id.buy_cb, R.id.sale_cb, R.id.sale_buy_layout, R.id.sale_cb_layout, R.id.minus_point_zero_one, R.id.add_point_zero_one, R.id.add_one, R.id.add_two, R.id.choose_stucks_layout, R.id.buy, R.id.market_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.minus_point_zero_one:
                float num3 = StringUtils.toFloat(showPrice.getText().toString());
                if (num3 > 0.01) {
                    num3 -= 0.01;
                }
                showPrice.setText(String.valueOf(MyUtil.formatBy2Float(num3, 2)));
                break;
            case R.id.add_point_zero_one:
                float num = StringUtils.toFloat(showPrice.getText().toString());
                num += 0.01;
                showPrice.setText(String.valueOf(MyUtil.formatBy2Float(num, 2)));
                break;
            case R.id.add_one:
                int num2 = StringUtils.toInt(showNumber.getText().toString());
                if (num2 > 1) {
                    num2 -= 1;
                }
                showNumber.setText(String.valueOf(num2));
                break;
            case R.id.add_two:
                int num1 = StringUtils.toInt(showNumber.getText().toString());
                num1 += 2;
                showNumber.setText(String.valueOf(num1));
                break;
            case R.id.buy_cb:
                select = "1";
                buyMark = "Purchase";
                buyCb.setChecked(true);
                saleCb.setChecked(false);
                break;
            case R.id.sale_cb:
                buyMark = "Sell";
                select = "2";
                buyCb.setChecked(false);
                saleCb.setChecked(true);
                break;
            case R.id.sale_buy_layout:
                select = "1";
                buyMark = "Purchase";
                buyCb.setChecked(true);
                saleCb.setChecked(false);
                break;
            case R.id.sale_cb_layout:
                select = "2";
                buyMark = "Sell";
                buyCb.setChecked(false);
                saleCb.setChecked(true);
                break;
            case R.id.choose_stucks_layout:
                break;
            case R.id.buy:
                if (StringUtils.isEmpty(showNumber.getText().toString())) {
                    ToastUtil.showToast("Please Input Number");
                    return;
                }
                if (StringUtils.isEmpty(showPrice.getText().toString())) {
                    ToastUtil.showToast("Please Input Price");
                    return;
                }
                showBuyStockDialog();
                break;
            case R.id.market_buy:
                if (StringUtils.isEmpty(showNumber.getText().toString())) {
                    ToastUtil.showToast("Please Input Number");
                    return;
                }
                if (StringUtils.isEmpty(showPrice.getText().toString())) {
                    ToastUtil.showToast("Please Input Price");
                    return;
                }
                showBuyStockDialog();
                break;

            default:
                break;
        }
    }

    private void showBuyStockDialog() {
        final Dialog dialog = new Dialog(BuySimulatedTransactionActivity.this, R.style.RcDialog);
        View view = LayoutInflater.from(BuySimulatedTransactionActivity.this).inflate(R.layout.dialog_purchase, null);
        TextView buyorsell = view.findViewById(R.id.buyorsell);
        TextView stocknames = view.findViewById(R.id.stockname);
        TextView price = view.findViewById(R.id.price);
        TextView number = view.findViewById(R.id.number);
        TextView allmoney = view.findViewById(R.id.allmoney);
        TextView cancels = view.findViewById(R.id.cancel);
        TextView yes = view.findViewById(R.id.yes);
        buyorsell.setText(buyMark);
        stocknames.setText(name);
        price.setText(showPrice.getText().toString());
        number.setText(showNumber.getText().toString());
        Float calprice = Float.valueOf(showPrice.getText().toString());
        Float calnumber = Float.valueOf(showNumber.getText().toString());
        float result = calprice * calnumber;
        allmoney.setText("$" + MyUtil.formatBy2Float(result, 2));
        cancels.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                submitPurchase();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.setContentView(view);
        if (!MyUtil.getActivity(dialog.getContext()).isFinishing()) {
            dialog.show();
        }

    }

    private void submitPurchase() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("symbols_id", symbold);
        jsonObject.addProperty("number", showNumber.getText().toString());
        jsonObject.addProperty("type", "2");
        jsonObject.addProperty("select", select);
        OkHttpUtils.getInstance().postWithMemberToken(Url.SUBMITORDER, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                                EventBus.getDefault().post(new RfreshStockDeal());
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }


}
